package org.xjtu.weteam.web.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.xjtu.weteam.common.JsonResponse;
import org.xjtu.weteam.common.utils.TokenUtils;
import org.xjtu.weteam.model.domain.User;
import org.xjtu.weteam.model.domain.UserTeam;
import org.xjtu.weteam.common.JsonResponse;
import org.xjtu.weteam.model.dto.UserDTO;
import org.xjtu.weteam.service.UserTeamService;
import org.xjtu.weteam.model.domain.Team;

import java.io.IOException;
import java.util.List;

import java.util.List;
import java.util.Objects;

/**
 * @author Kevin
 */
@RestController
@RequestMapping("/api/userTeam")
public class UserTeamController {

    private final Logger logger = LoggerFactory.getLogger(UserTeamController.class);

    @Autowired
    private UserTeamService userTeamService;

    @PostMapping("/getTeamUsers")
    @ResponseBody
    public JsonResponse getTeamUsers(Integer teamId) throws IOException {
        List<UserDTO> userDTOS = userTeamService.selectUsersWithAvatar(teamId);
        return JsonResponse.success(userDTOS);
    }


    @GetMapping("/getAllUsers")
    @ResponseBody
    public JsonResponse getAllUsers(Integer teamid){
        List<User> users = userTeamService.selectAllUsers(teamid);
        return JsonResponse.success(users);
    }

    @PostMapping("/removeRelationship")
    public JsonResponse removeRelationship(@RequestHeader("X-Access-Token") String token, Integer teamId){
        Integer userId = TokenUtils.getIdFromToken(token);
        userTeamService.removeRelationship(userId, teamId);
        return JsonResponse.success(true);
    }

    public Boolean checkIfIn(Integer teamId, Integer userId){
        return userTeamService.checkIfIn(teamId, userId);
    }
    @PostMapping("ifCreator")
    @ResponseBody
    public JsonResponse ifCreator(Integer teamId, @RequestHeader("X-Access-Token") String token){
        Integer userId = TokenUtils.getIdFromToken(token);
        Boolean isCreator = userTeamService.ifCreator(teamId, userId);
        return JsonResponse.success(isCreator);
    }

    @PostMapping("changeCreator")
    @ResponseBody
    public JsonResponse changeCreator(Integer teamId, Integer userId, @RequestHeader("X-Access-Token") String token){
        if(Objects.equals(TokenUtils.getIdFromToken(token), userId)){
            return JsonResponse.success(false, "选择了自己");
        }else {
            userTeamService.changeCreator(teamId, userId);
            return JsonResponse.success(true, "更换创建人");
        }
    }
}
